//
//  JXHomeViewController.swift
//  swift高仿微博
//
//  Created by peijiaxing on 16/2/24.
//  Copyright © 2016年 peijiaxing. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD


let JXHomeVCReuserID = "JXHomeViewControllerReuserIdenfiter"

class JXHomeViewController: JXBaseTableViewController {
    
    // 创建ViewModel的实例
    var statusListViewModel: JXStatusListViewModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        visitor?.setupInfo(nil, message: "关注一些人，回这里看看有什么惊喜",animation:true)
    
        // 判断是否登录
        
        if isLogin{
           
            statusListViewModel = JXStatusListViewModel()
            
//            statusListViewModel?.loadData({ () -> () in
//                self.tableView.reloadData()
//            })
            
            loadData()
            // 注册 cell
            tableView.registerClass(JXHomeTableViewCell.self, forCellReuseIdentifier: JXHomeVCReuserID)
            // 自动计算行高
            tableView.rowHeight = UITableViewAutomaticDimension
            // 给cell一个预估行高
            tableView.estimatedRowHeight = 85
            
            
            tableView.tableFooterView = pullView
            
            tableView.addSubview(refreshView)
            
            refreshView.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        }
   
    }
    
    func loadData(){
        
        SVProgressHUD.show()
        
        var since_id = statusListViewModel?.array.first?.statusModel?.id ?? 0
        
        var max_id = 0
        
        if pullView.isAnimating(){
            
            since_id = 0
            // 拿到最后一条数据
            max_id = statusListViewModel?.array.last?.statusModel?.id ?? 0
            
            max_id -= 1
        }
        
        statusListViewModel?.loadData(since_id, max_id: max_id, finish: { (count :Int) -> () in
            
            self.tableView.reloadData()
            
            //菊花转的时候,肯定是上体更多
            if !self.pullView.isAnimating() {
                //显示刷新提示
                self.showNewCount(count)
            }
            
            // 还原加载标记
            self.pullView.stopAnimating()
            
            SVProgressHUD.dismiss()
            
            self.refreshView.endRefreshing()
        })
        

        
    }
    
    private func showNewCount(count: Int){
        
        // 创建视图
        let ShowMessageLabel = UILabel(frame: CGRectMake(0,64 - 44,UIScreen.mainScreen().bounds.size.width,44))
        ShowMessageLabel.backgroundColor = UIColor.orangeColor()
        
        if count > 0{
            ShowMessageLabel.text = "更新了\(count)条微博"
        }else{
            ShowMessageLabel.text = "暂无更新"
        }
        ShowMessageLabel.textAlignment = .Center
        ShowMessageLabel.textColor = UIColor.blackColor()
        ShowMessageLabel.font = UIFont.systemFontOfSize(15)
        
        // 添加到视图里
        self.navigationController?.view.insertSubview(ShowMessageLabel, belowSubview: (navigationController?.navigationBar)!)
        UIView.animateWithDuration(2, animations: { () -> Void in
            ShowMessageLabel.transform = CGAffineTransformMakeTranslation(0, 44)
            }) { (_) -> Void in
                //当动画完成之后,隐藏
                UIView.animateWithDuration(2, animations: { () -> Void in
                    // 回去 -- 回到原点 CGAffineTransformIdentity
                    ShowMessageLabel.transform = CGAffineTransformIdentity
                    
                    }, completion: { (_) -> Void in
                        //销毁或者隐藏
                        ShowMessageLabel.removeFromSuperview()
                })
        }
        
        
    }

    // 懒加载
    
    private lazy var pullView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    private lazy var refreshView: JXRefreshView = JXRefreshView()
}




extension JXHomeViewController{
    // 数据源加载
    
    
            // 返回行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusListViewModel?.array.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(JXHomeVCReuserID, forIndexPath: indexPath) as! JXHomeTableViewCell
        
        cell.statusViewModel = statusListViewModel?.array[indexPath.row]
        
//        if indexPath.row == (statusListViewModel!.array.count - 1) && !pullView.isAnimating(){
//          
//            pullView.startAnimating()
//            
//            loadData()
//            
//            printLog("上拉更多")
//        }
        
        if indexPath.row == (statusListViewModel!.array.count - 1) && !pullView.isAnimating() {
            
            pullView.startAnimating()
            loadData()
            
            print("上拉更多")
        }
        
        return cell
        
    }
       
}
